package com.songshuai.customer.client.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.songshuai.customer.client.service.CustomerInfoService;
import com.songshuai.customer.client.service.WxPlatformService;
import com.songshuai.webapi.baseapi.constant.miniprogram.CacheKeys;
import com.songshuai.webapi.baseapi.enumerations.miniprogram.ResponseStatus;
import com.songshuai.webapi.baseapi.exception.BusinessException;
import com.songshuai.webapi.baseapi.model.sales.CustomerInfo;
import com.songshuai.webapi.baseapi.model.sales.WxPlatform;
import com.songshuai.webapi.common.httpclient.HttpClientUtil;
import com.songshuai.webapi.common.redis.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author:wbl
 * @Date: 2019/3/22
 */
public class BaseController {

    @Autowired
    public RedisUtil redisUtil;

    @Autowired
    protected WxPlatformService wxPlatformService;

    @Autowired
    protected CustomerInfoService customerInfoService;

    @Autowired
    protected HttpServletRequest request;

    public String getAccessTokenByAppId(String appId){
        String accessToken = redisUtil.getString(appId);
        if(StringUtils.isBlank(accessToken)) {
            //String wxspAppid = "wxb2cb3caa4ff29b27";
            // 小程序的 app secret (在微信小程序管理后台获取)
            String wxspSecret = "f5c96e1d1241463746731b651829c045";
            //这里直接写死就可以，不用改，用法可以去看api
            String grant_type = "client_credential";
            //封装请求数据
            String params = "grant_type=" + grant_type + "&secret=" + wxspSecret + "&appid=" + appId;
            //发送GET请求
            String sendGet = HttpClientUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
            // 解析相应内容（转换成json对象）
            JSONObject json = JSON.parseObject(sendGet);
            //拿到accesstoken
            if (ResponseStatus.ACCESS_TOKEN_ERRCODE.getErrorCode() == json.getInteger("errcode")) {
                throw new BusinessException(ResponseStatus.ACCESS_TOKEN_ERRCODE);
            }
            if (ResponseStatus.ACCESS_TOKEN_ERRCODE_40001.getErrorCode() == json.getInteger("errcode")) {
                throw new BusinessException(ResponseStatus.ACCESS_TOKEN_ERRCODE_40001);
            }
            if (ResponseStatus.ACCESS_TOKEN_ERRCODE_40002.getErrorCode() == json.getInteger("errcode")) {
                throw new BusinessException(ResponseStatus.ACCESS_TOKEN_ERRCODE_40002);
            }
            if (ResponseStatus.ACCESS_TOKEN_ERRCODE_40013.getErrorCode() == json.getInteger("errcode")) {
                throw new BusinessException(ResponseStatus.ACCESS_TOKEN_ERRCODE_40013);
            }
            accessToken = json.getString("access_token");
            redisUtil.set(appId, accessToken, 7200);
        }
        return accessToken;
    }


    //获取微信平台信息
    public WxPlatform getWxPlatform(String appid){
        Object o= redisUtil.hget(appid,CacheKeys.WXPLATFORM_KEY);
        WxPlatform wxPlatform=null;
        if(null!=o){
            wxPlatform=(WxPlatform)o;
            return wxPlatform;
        }else{
            wxPlatform = wxPlatformService.selectByEntity(new WxPlatform() {{
                setAppId(appid);
            }});
            redisUtil.hset(appid,CacheKeys.WXPLATFORM_KEY,wxPlatform,CacheKeys.ONE_DAY);
            return wxPlatform;
        }
    }

    public String getCurrentToken(){
        Object token = request.getHeader("token");
        if(null!=token){
            return (String)token;
        }else{
            return null;
        }
    }


    //获取当前用户openid   使用时记得判空
    public String getCurrentCustomerOpenid() {
        String token = getCurrentToken();
        if (StringUtils.isNotBlank(token)) {
            Object o = redisUtil.hget(token, CacheKeys.OPENID);
            if (null != o) {
                return (String) o;
            } else {
                CustomerInfo customerInfo = customerInfoService.selectByEntity(new CustomerInfo() {{
                    setToken(token);
                }});
                if (null != customerInfo) {
                    return customerInfo.getOpenId();
                } else {
                    return null;
                }
            }
        } else {
            return null;
        }
    }
    //获取当前用户customerId   使用时记得判空
    public String getCurrentcustomerId () {
        String token = getCurrentToken();
        if (StringUtils.isNotBlank(token)) {
            Object o = redisUtil.hget(token, CacheKeys.PANGU_CUST_ID);
            if (null != o) {
                return (String) o;
            } else {
                CustomerInfo customerInfo = customerInfoService.selectByEntity(new CustomerInfo() {{
                    setToken(token);
                }});
                if (null != customerInfo) {
                    return customerInfo.getUserId();
                } else {
                    return null;
                }
            }
        } else {
            return null;
        }
    }

}
